<template>
  <div class="patient-reported-right-list">
    <div class="list-header">
      <el-button v-if="permissionController('subject::ecrf::data::entery')" size="mini" @click="handleAdded">增加</el-button>
    </div>
    <div v-if="show" class="main">
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane
          v-for="(tab, index) in tabs"
          :label="`${tab.label}(${tab.data.length})`"
          :name="tab.name"
          :key="index"
        >
          <el-table
            size="mini"
            :stripe="true"
            :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }"
            :data="tab.data"
            style="width: 100%;overflow: auto;display:grid"
            @row-dblclick="handleRowDblclick"
            :row-class-name="tableRowClassName"
          >
            <el-table-column width="65">
              <template slot-scope="scope">
                <span :class="`left-icon question question-${handleQuestionStatus(scope.row.entity)}`"></span>
                <span class="audit-box">
                  <span
                    v-for="(audit, index) in audits"
                    :title="audit.checkName"
                    :key="index"
                    :class="`left-icon audit audit-${findAuditState(audit, scope.row.entity)}`"
                  >
                  </span>
                </span>
              </template>
            </el-table-column>
            <el-table-column
              v-for="(title, index) in titles"
              :minWidth="title.width"
              :label="title.variableName"
              :key="index"
            >
              <template slot-scope="scope">
                {{
                  (scope.row[title.variable] + '').startsWith('https://')
                    ? `${scope.row[title.variable].substring(0, 10)}...`
                    : scope.row[title.variable]
                }}
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="footer"></div>
    <el-drawer
      :with-header="false"
      :modal="false"
      :wrapper-closable="false"
      :destroy-on-close="true"
      :visible.sync="dialog"
      direction="rtl"
      size="76%"
    >
      <div class="close-box">
        <i class="el-icon-close" @click="handleClose"></i>
      </div>
      <right-form v-if="dialog" :source="target" :addSortNum="addSortNum" :original="original" :isAddList="isAddList" :isAddEm="isAddEm" channel="list" @uploadList="uploadList"/>
    </el-drawer>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import RightForm from './form'
import { permissionController } from '@/utils/index'

export default {
  data() {
    return {
      activeName: 'first',
      tabs: [
        {
          label: '全部',
          name: 'first',
          data: [],
        },
        {
          label: '生效',
          name: 'second',
          data: [],
        },
        { label: '失效', name: 'third', data: [] },
      ],
      show: false,
      titles: [],
      target: null,
      original: null,
      dialog: false,
      isAddEm: false,
      isAddList: false,
      addSortNum: 0,
      operate: false
    }
  },
  props: {
    source: {
      type: [Object, Array],
    },
  },
  components: { RightForm },
  computed: {
    ...mapState({
      audits: state => state.treatment.audits,
      table: state => state.treatment.table,
      stateOptions: state => state.treatment.stateOptions,
      frozenOptions: state => state.treatment.frozenOptions,
    }),
  },
  watch: {
    source: {
      handler: function (val) {
        if (val) {
          if (this.operate) {
            this.target = JSON.parse(JSON.stringify(val[val.length-1]))
            this.original = JSON.parse(JSON.stringify(val[val.length-1]))
          }
        } else {
          this.reset()
        }
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    if (this.source) {
      this.handleTable()
    } else {
      this.reset()
    }
  },
  methods: {
    permissionController,
    handleAdded () {
      if (this.dialog && this.isAddList) {
        return
      }
      this.operate = false
      this.isAddList = true
      if (this.source instanceof Array) {
        if (this.source.length > 0) {
          this.target = JSON.parse(JSON.stringify(this.source[0]))
          this.target.embeddedTable = {}
          delete this.target.tableStatus
          this.original = JSON.parse(JSON.stringify(this.source[0]))
          delete this.original.tableStatus
        }
      } else {
        this.target = JSON.parse(JSON.stringify(this.source))
        this.original = JSON.parse(JSON.stringify(this.source))
      }
      this.target.mainTable.tableFieldList.forEach(tableField => {
        tableField.variableValue = ''
      })
      // this.original = null
      this.dialog = true
      this.isAddEm = true
      const list = this.source.filter(item=>item.tableStatus !== null)
      this.addSortNum = list.length + 1
    },
    findAuditState (audit, entity) {
      const { roleCode } = audit
      let roleCodes = roleCode
      if (roleCode === 'Medical') {
        roleCodes = 'mm'
      }
      if (roleCode === 'Site_PI') {
        roleCodes = 'pi'
      }
      if (roleCodes) {
        const target = ['statisticsCra', 'statisticsDm', 'statisticsMm', 'statisticsPi', 'statisticsPm'].filter(
        key => key.toLowerCase() === `statistics${roleCodes.toLowerCase()}`
        )[0]
      const { tableStatus } = entity
      return tableStatus[target]
      }
      
    },
    handleQuestionStatus(entity) {
      const {
        tableStatus: { statisticsQuestion },
      } = entity
      return statisticsQuestion == 2 ? (this.permissionController('send::challenge')? '2-2' : '2-1') : statisticsQuestion
    },
    handleClose() {
      this.dialog = false
      this.handleTable()
    },
     //指定行颜色
     tableRowClassName: function({ row, rowIndex }) {
      if (row.isLapse === '失效') {
        return 'rowActive';
      }
    },
    uploadList () {
      this.operate = true
      this.isAddList = false
      this.$emit('upload')
    },
    handleTable() {
      this.reset()
      if (this.source instanceof Array) {
        if (this.source.length > 0) {
          const {
            mainTable: { tableFieldList },
            tableStatus,
          } = this.source[0]
          this.hendleTitle(tableFieldList)
          if (tableStatus) {
            this.handleList()
          }

          this.show = false
          this.$nextTick(() => {
            this.show = true
          })
        }
      } else {
        const {
          mainTable: { tableFieldList },
        } = this.source
        this.hendleTitle(tableFieldList)
        this.show = false
        this.$nextTick(() => {
          this.show = true
        })
      }
    },
    reset: function () {
      this.tabs = [
        {
          label: '全部',
          name: 'first',
          data: [],
        },
        {
          label: '生效',
          name: 'second',
          data: [],
        },
        { label: '失效', name: 'third', data: [] },
      ]
      this.titles.length = 0
    },
    handleRowDblclick(row) {
      const array = []
      array.push(row.entity)
      this.target = array
      this.original = JSON.parse(JSON.stringify(array))
      this.dialog = true
      this.isAddEm = false
    },
    // 判断ecrf状态
    findTableState(tableStatus) {
      if (tableStatus) {
        const { isStatus, frozen, isLapse } = tableStatus
        if (isLapse === '2') {
          return '失效'
        } else if (frozen === '1') {
          return this.stateOptions[isStatus]
        } else {
          return this.frozenOptions[frozen]
        }
      } else {
        return ''
      }
    },
    // 表格数据处理
    handleList() {
      this.source.forEach(subjectData => {
        const {
          mainTable: { tableFieldList },
          tableStatus,
        } = subjectData
        const { isLapse } = tableStatus
        const obj = { entity: subjectData }
        obj['isLapse'] = isLapse === '1' ? '生效' : '失效'
        obj['CRFStatus'] = this.findTableState(tableStatus)
        obj['sortNum'] = tableStatus.sortNum
        tableFieldList.forEach(tableField => {
          const { variable, variableType, variableValue, databaseCodeValueDTO } = tableField
          if (variableValue) {
            if (variableType === '10') {
              const target = databaseCodeValueDTO.filter(item => item.codeValue == variableValue)
              if (target && target.length > 0) {
                obj[variable] = target[0].codeDescribe
              }
            } else if (variableType === '20') {
              const arr = variableValue.split(',')
              obj[variable] = arr
                .map(v => {
                  const { codeDescribe } = databaseCodeValueDTO.filter(item => item.codeValue == v)[0]
                  return codeDescribe
                })
                .join(',')
            } else {
              obj[variable] = variableValue
            }
          } else {
            obj[variable] = ''
          }
        })
        this.tabs[0].data.push(obj)
        if (isLapse === '1') {
          this.tabs[1].data.push(obj)
        } else if (isLapse === '2'||isLapse === '3') {
          this.tabs[2].data.push(obj)
        }
      })
    },
    hendleTitle(tableFieldList) {
      this.titles.length = 0
      this.titles = tableFieldList
        .filter(tableField => tableField.type === '1')
        .map(tableField => {
          return {
            variable: tableField.variable,
            variableName: tableField.variableName,
          }
        })
      const sort = {
        variable: 'sortNum',
        variableName: '序号',
        width: 60,
      }
      this.titles.splice(0, 0, sort)
      const curStatus = {
        variable: 'isLapse',
        variableName: '生效/失效',
        width: 120,
      }

      this.titles.splice(1, 0, curStatus)
      this.titles.push({
        variable: 'CRFStatus',
        variableName: 'CRF状态',
        width: 100,
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.patient-reported-right-list {
  display: flex;
  flex-flow: column nowrap;
  height: 100%;
  padding: 0 0.9375rem;

  > .list-header {
    flex: 55;
    display: flex;
    justify-content: flex-start;
    align-items: center;

    > .el-button {
      padding: 7px 10px;
    }
  }

  > .main {
    flex: 839;

    /deep/ {
      .el-tabs__header {
        margin: 0 0 0.6rem;
      }

      .el-tabs__item:hover,
      .el-tabs__item.is-active {
        color: #6b1685;
      }

      .el-tabs__item {
        height: 2.14rem;
        line-height: 2.14rem;
      }
    }

    border-bottom: 1px solid #f0f0f0;

    i {
      color: #b4b4b4;
      font-size: 0.8rem;

      &:last-child {
        position: relative;
        left: 0.3rem;
      }
    }

    /deep/ {
      .el-tabs__header {
        margin: 0 0 0.6rem;
      }

      .el-tabs__item:hover,
      .el-tabs__item.is-active {
        color: #6b1685;
      }

      .el-tabs__item {
        height: 2.14rem;
        line-height: 2.14rem;
      }
    }

    .question {
      margin-right: 0.4rem;
    }

    .left-icon {
      display: inline-block;
    } 

    .audit,
    .question {
      width: 0.2rem;
      height: 0.75rem;
      background-size: 0.2rem 0.75rem;
    }

    .audit-box {
      display: inline-grid;
      grid-template-columns: repeat(5, 1fr);

      > .audit {
        width: 0.25rem;
        height: 0.75rem;
        background-size: 0.25rem 0.75rem;
        margin: 0 0.025rem;
      }
      >.audit-1,
      >.audit--1 {
        background-image: url("~@/assets/img/audit-1.png");
      }

      >.audit-2 {
        background-image: url("~@/assets/img/audit-2.png");
      }

      >.audit-3 {
        background-image: url("~@/assets/img/audit-3.png");
      }
    }

    .question {
      position: relative;
      left: 0.1rem;
      width: 0.7rem;
      height: 0.65rem;
      background-size: 0.7rem 0.65rem;
    }
    .question-1 {
      cursor: not-allowed;
      background-image: url('~@/assets/img/question-1.png');
    }
    .question-2-1 {
          background-image: url('~@/assets/img/question-2-1.png');
        }

        .question-2-2 {
          background-image: url('~@/assets/img/question-2-2.png');
        }

        .question-3 {
          background-image: url('~@/assets/img/question-3.png');
        }
  }

  .close-box {
    height: 1.5rem;
    display: flex;
    justify-content: flex-start;

    i {
      position: relative;
      left: 0.95rem;
      top: 0.3rem;
      font-size: 1.12rem;
      font-weight: 500;
    }
  }

  .el-drawer__wrapper {
    position: absolute;
  }

  /deep/ .rowActive {
    color: #acadad;
  }
  .z-index999 {
    z-index: 9999999;
  }

}
</style>
